package fr.inserm.um915.bdibd.model;

public class ChromStartEnd
	implements Comparable<ChromStartEnd>
	{
	private byte chrom;
	private int start;
	private int end;
	
	
	public ChromStartEnd(String chrom,int start,int end)
		{
		this.chrom=ChromPosition.normalize(chrom);
		this.start=start;
		this.end=end;
		}
	
	public ChromStartEnd(byte chrom,int start,int end)
		{
		this.chrom=chrom;
		this.start=start;
		this.end=end;
		}
	
	
	@Override
	public int compareTo(ChromStartEnd o)
		{
		int i= (int)(chrom)- (int)(o.chrom);
		if(i!=0) return i;
		i= start-o.start;
		if(i!=0) return i;
		i= end-o.end;
		return i;
		}
	
	
	
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + (int)(chrom);
		result = prime * result + start;
		result = prime * result + end;
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		ChromStartEnd other = (ChromStartEnd) obj;
		return this.compareTo(other)==0;
	}

	public byte getChromosomeId()
		{
		return this.chrom;
		}
	
	public String getChromosome()
		{
		return ChromPosition.denormalize(this.chrom);
		}
	
	public int getStart()
		{
		return start;
		}
	public int getEnd()
		{
		return end;
		}
	
	@Override
	public String toString()
		{
		return getChromosome()+":"+start+"-"+end;
		}
	
	
	static ChromStartEnd parse(String s)
		{
		if(s==null) return null;
		s=s.trim();
		int colon=s.indexOf(':');
		byte b=-1;
		if(colon==-1)
			{
			try
				{
				b=ChromPosition.normalize(s);
				return new ChromStartEnd(b, 0, 300000000);
				}
			catch(Throwable err)
				{
				return null;
				}
			}
		String c=s.substring(0,colon).trim();
		
		try
			{
			b=ChromPosition.normalize(c);
			}
		catch(Throwable err)
			{
			return null;
			}
		if(b==-1) return null;
		int dash=s.indexOf('-',colon+1);
		if(dash==-1)
			{
			return new ChromStartEnd(b, 0, 300000000);
			}
		try
			{
			return new ChromStartEnd(b,
				Integer.parseInt(s.substring(colon+1,dash).trim()),
				Integer.parseInt(s.substring(dash+1).trim())
				);
			}
		catch(Throwable err)
			{
			return null;
			}
		}
	}
